package com.medusa.gruul.payment.service.handler.verify;

import cn.hutool.core.util.StrUtil;
import com.medusa.gruul.common.web.handler.Handler;
import com.medusa.gruul.payment.api.enums.TradeStatus;
import com.medusa.gruul.payment.service.common.model.OrderPaymentRecord;
import com.medusa.gruul.payment.service.service.MultiPayOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 支付状态校验处理器
 *
 * @author xiaoq
 * @ Description AbstractPayStatusVerifyHandler.java
 * @date 2022-08-01 15:49
 */
@Slf4j
@RequiredArgsConstructor
public abstract class AbstractPayStatusVerifyHandler implements Handler<TradeStatus> {

    private final MultiPayOrderService multiPayOrderService;

    /**
     * 处理参数
     *
     * @param params 参数
     * @return 返回内容 <T>返回数据类型
     */
    @Override
    public TradeStatus handle(Object... params) {
        if (hasErrorParam(params, String.class)) {
            throw new IllegalArgumentException("params required string type");
        }
        String outTradeNo = cast(params[0], String.class);

        if (StrUtil.isBlank(outTradeNo)) {
            throw new IllegalArgumentException("outTradeNo is null");
        }

        OrderPaymentRecord paymentRecord = multiPayOrderService.paymentRecord(outTradeNo);
        TradeStatus status = handle(paymentRecord.getDetailsId(), outTradeNo);
        log.debug("支付状态检查结果:{}", status);
        return status;
    }

    /**
     * handle
     *
     * @param detailsId  商户支付配置列表id
     * @param outTradeNo 业务单号
     * @return 交易状态
     */
    protected abstract TradeStatus handle(String detailsId, String outTradeNo);
}
